#ifndef STACK
#define STACK

#include <stdlib.h>
#include <malloc.h>

#include "poly.h"

// 栈中元素的类型，可储存多项式、数字或运算符
typedef struct
{
    Poly *poly;
    double num;
    char oprt;
} Elem, *Elemptr;

// 判断元素是不是多项式
int IsPoly(Elem *elem)
{
    return elem->poly != 0;
}

// 判断元素是不是数字
int IsNum(Elem *elem)
{
    return elem->poly == 0 && elem->oprt == 0;
}

// 判断元素是不是运算符
int IsOprt(Elem *elem)
{
    return elem->oprt != 0;
}

// 创建新元素
Elem *NewElem(Poly *poly, double num, char oprt)
{
    Elem *elem = (Elem *)malloc(sizeof(Elem));
    elem->poly = poly;
    elem->num = num;
    elem->oprt = oprt;
    return elem;
}

// 栈类型
typedef struct
{
    Elemptr data[100];
    int size;
} Stack;

// 创建新栈
Stack *NewStack()
{
    Stack *stack = (Stack *)malloc(sizeof(Stack));
    stack->size = 0;
    return stack;
}

// 栈的大小
int Size(Stack *stack)
{
    return stack->size;
}

// 入栈
void Push(Stack *stack, Elemptr elem)
{
    stack->data[stack->size++] = elem;
}

// 出栈
Elemptr Pop(Stack *stack)
{
    if (stack->size > 0)
    {
        return stack->data[--stack->size];
    }
    else
    {
        return NULL;
    }
}

// 获取栈顶
Elemptr Top(Stack *stack)
{
    if (stack->size > 0)
    {
        return stack->data[stack->size - 1];
    }
    else
    {
        return NULL;
    }
}

// 清空栈
void ClearStack(Stack *stack)
{
    for (int i = 0; i < stack->size; i++)
    {
        if (IsPoly(stack->data[i]))
        {
            ClearPoly(stack->data[i]->poly);
            free(stack->data[i]->poly);
        }
        free(stack->data[i]);
    }
    stack->size = 0;
}

#endif
